﻿#region Used Namespaces

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using AutoUnzip.Interfaces;
using SevenZip;

#endregion

namespace AutoUnzip.Core
{
    public class ZipSerivce : IZipSerivce
    {
        public long TotalZipSize { get; set; }
        
        public async Task<bool> UnzipAsync(string archive, string outDirectory, CancellationToken cancellationToken, IProgress<long> progress)
        {
            try
            {
                using (var zipExtractor = new SevenZipExtractor(archive))
                {
                    var tcs = new TaskCompletionSource<bool>();
                    cancellationToken.Register(() => tcs.SetResult(false));

                    zipExtractor.Extracting += (sender, args) => progress.Report(args.PercentDelta);
                    zipExtractor.ExtractionFinished += (sender, args) => tcs.SetResult(true);
                    zipExtractor.BeginExtractArchive(outDirectory);

                    return await tcs.Task;
                }
            }
            catch (Exception exception)
            {
                return false;
            }
        }

        public IEnumerable<string> GetFilesFromArchive(string archive)
        {
            try
            {
                using (var zipExtractor = new SevenZipExtractor(archive))
                {
                    return zipExtractor.VolumeFileNames;
                }
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
